package com.jsonpfy.webservices;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.jsonpfy.operations.ListData;

@SuppressWarnings("serial")
public class ListDataServlet extends HttpServlet {

	// http://localhost:8888/ListDataService
	// ?kind=Comment
	// &filterField=projectID&filterValue=Projectnection
	// &filterField=classPath&filterValue=com.projectnection.client.Entities.EntityPage
	// &sortField=date&sortDirection=desc

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		JSONArray entities = null;

		String kind = request.getParameter("kind");

		String filterField1 = request.getParameter("filterField1");

		String filterField2 = request.getParameter("filterField2");

		String filterField3 = request.getParameter("filterField3");

		String filterField4 = request.getParameter("filterField4");

		String sortField = request.getParameter("sortField");

		String sortDirection = request.getParameter("sortDirection");

		if (filterField1 != null) {

			String filterValue1 = request.getParameter("filterValue1");

			String filterValue2 = request.getParameter("filterValue2");

			String filterValue3 = request.getParameter("filterValue3");

			String filterValue4 = request.getParameter("filterValue4");

			entities = ListData.jsonListFilter(kind, filterField1,
					filterField2, filterField3, filterField4, filterValue1,
					filterValue2, filterValue3, filterValue4, sortField,
					sortDirection);

		} else {

			String filterKeyField = request.getParameter("filterKeyField");

			if (filterKeyField != null) {

				String filterKeyKind = request.getParameter("filterKeyKind");

				String filterKeyValue = request.getParameter("filterKeyValue");

				entities = ListData
						.jsonListFilterKey(kind, filterKeyField, filterKeyKind,
								filterKeyValue, sortField, sortDirection);
			} else {

				entities = ListData.jsonList(kind, sortField, sortDirection);
			}
		}

		String answer = Utilities.getCallback(request.getParameter("callback"),
				entities.toString());

		response.getWriter().println(answer);
	}
}
